package me.stone.stanimeclient.core.common.extensions

import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlin.time.Duration


fun <T> Flow<T>.throttle(timeMillis: Duration): Flow<T> = throttle(timeMillis.inWholeMilliseconds)

fun <T> Flow<T>.throttle(timeMillis: Long): Flow<T> = flow {
    var lastTime = 0L
    collect {
        if (System.currentTimeMillis() - lastTime > timeMillis) {
            emit(it)
        }
        lastTime = System.currentTimeMillis()
    }
}

fun <E> SendChannel<E>.tryOffer(element: E): Boolean = try {
    trySend(element).isSuccess
} catch (t: Throwable) {
    false
}